package com.gainloop.Listeners;

import java.util.ArrayList;

import com.gainloop.Api.Entity.Category;
import com.gainloop.Utils.Constants;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * This class will handle the item select event in the Category Spinner.
 * @author Meir
 *
 */
public class CategorySpinnerListener implements OnItemSelectedListener{
	
	Intent _intent;
	ArrayList<Category> _allCategories;

	public CategorySpinnerListener(Intent intent,ArrayList<Category> allCategories){
		_intent = intent;
		_intent.putExtra(Constants.CATEGORY_ID, allCategories.get(0).getId());
		
		_allCategories = allCategories;
		
		
	}

	public void onItemSelected(AdapterView<?> parent,
			View view, int pos, long id) {
		String chosenCategoryStr = parent.getItemAtPosition(pos).toString();
		if(chosenCategoryStr.compareTo(Constants.ALL_CATEGORY)==0){
			_intent.putExtra(Constants.CATEGORY_ID, Constants.ALL_CATEGORY_ID);
			return;
		}
		Long _chosenCategoryId = getCategoryId(chosenCategoryStr);
		
		//I'm saving the current CATEGORY_ID on the intent, it is maybe nicer to use global param, may change it in future...- Meir
		_intent.putExtra(Constants.CATEGORY_ID, _chosenCategoryId);
		Log.v("chosenCategoryId",Long.toString(_chosenCategoryId));
	}

	@SuppressWarnings("rawtypes")
	public void onNothingSelected(AdapterView parent) {
		// Do nothing.
	}
	
	/**
	 * Finds the category Id according to its String representation. 
	 * @param chosenCategoryStr
	 * @return null if not found, else the category id.
	 */
	private Long getCategoryId(String chosenCategoryStr) {
		for(Category curCategory:_allCategories){
			if(curCategory.getName().compareTo(chosenCategoryStr)==0){
				return curCategory.getId();
			}
		}
		return null;
	}

}
